package cn.com.zhuxulin.info.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public final class HttpRequest {
	public static String doPost(String url, String xml) throws Exception {
		byte[] b = new byte[4096];
		// InputStream in = HttpRequest.class.getResourceAsStream(xml);
		HttpConnection conn = (HttpConnection) Connector.open(url);
		conn.setRequestMethod(HttpConnection.POST);
		conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(xml.getBytes().length));
		conn.openOutputStream().write(xml.getBytes());
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		InputStream in = conn.openInputStream();
		while (in.read(b) != -1) {
			out.write(b);
		}
		if (conn.getResponseCode() == 200) {
			return IOUtils.BytesToString(b, "UTF-8");
		}
		System.out.println("Code:" + conn.getResponseCode());
		System.out.println(IOUtils.BytesToString(b, "UTF-8"));
		return "error";
	}
	public static InputStream doPostForInputStream(String url, String xml) throws Exception {
		HttpConnection conn = (HttpConnection) Connector.open(url);
		conn.setRequestMethod(HttpConnection.POST);
		conn.setRequestProperty("Content-Type", "application/soap+xml; charset=utf-8");
		conn.setRequestProperty("Content-Length", String.valueOf(xml.getBytes().length));
		conn.openOutputStream().write(xml.getBytes());
		return conn.openInputStream();
	}

	public static String doGet(String url) throws IOException {
		byte[] b = new byte[2048];
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		HttpConnection conn = (HttpConnection) Connector.open(url);
		InputStream in = conn.openInputStream();
		while (in.read(b) != -1) {
			out.write(b);
		}
		if (conn.getResponseCode() == 200) {
			return IOUtils.BytesToString(b, "UTF-8");
		}
		System.out.println("Code:" + conn.getResponseCode());
		System.out.println(IOUtils.BytesToString(b, "UTF-8"));
		return "error";
	}
	public static InputStream doGetForInputStream(String url) throws IOException {
		HttpConnection conn = (HttpConnection) Connector.open(url);
		return conn.openInputStream();
	}
}
